# This script is used to generate the app
import os
import json

# from backend_django.local_settings import INSTALLED_APPS
from script.exec_sys_cmd import execute_sys_cmd


def create_urls(project_path, app_name):
    urls_path = os.path.join(project_path, app_name, "urls.py")
    template_urls = os.path.join(project_path, "template", "back_end_template", "template_urls.html")
    with open(urls_path, "w+") as fw:
        with open(template_urls, "r+") as fr:
            fw.write(fr.read().replace("{app}", app_name))


def update_base_urls(project_path, app_name):
    base_urls_path = os.path.join(project_path, "backend_django", "urls.py")
    template_base_urls = os.path.join(project_path, "template", "back_end_template", "template_base_urls.html")
    with open(base_urls_path, "r+") as fw:
        fw_content = fw.read()
        with open(template_base_urls, "r+") as fr:
            fr_content = fr.read().replace("{app}", app_name)
            print(fr_content)
            f_content = fw_content.replace("]", fr_content)
            print(f_content)
            with open(base_urls_path, "w") as f:
                f.write(f_content)


def update_models(project_path, app_name):
    # project_path = os.path.dirname(os.path.dirname(__file__))
    models_test_path = os.path.join(project_path, app_name, "models_test.py")
    models_app_path = os.path.join(project_path, app_name, f"models_{app_name}.py")
    to_dict = {
    }
    with open(models_app_path, "r+") as fw:
        fw_content_list = fw.readlines()
        with open(models_test_path, 'a+') as f:
            for i in fw_content_list:
                if "from django.db import models" in i or i.startswith("#"):
                    continue
                if "Field" in i:
                    field = i.split("=")
                    field_name = field[0].strip()
                    if "DateTimeField" in field[1]:
                        to_dict[field_name] = f"self.{field_name}.strftime('%Y-%m-%d %H:%M:%S')"
                    else:
                        to_dict[field_name] = f"self.{field_name}"
                f.write(i)
            content = "    def to_dict(self):\n"
            content += "        return {\n"
            content += "            'id': self.id,\n"
            for k, v in to_dict.items():
                content += f"            '{k}': {v},\n"
            content += "        }\n"
            f.write(content)


def generate_views(project_path, table_name, app_name: str):
    # project_path = os.path.dirname(os.path.dirname(__file__))
    base_views_path = os.path.join(project_path, app_name, f"{app_name}_views.py")
    template_base_views = os.path.join(project_path, "template", "back_end_template", "template_views.html")
    with open(base_views_path, "w+") as fw:
        with open(template_base_views, "r+") as fr:
            fr_content = fr.read().replace("{app}", app_name).replace(
                "{model_table}", table_name.capitalize()).replace("{table_name}", table_name)
            fw.write(fr_content)


def generate_app(app_name):
    generate_django_app = f"python manage.py startapp {app_name}"
    ret_code, res = execute_sys_cmd(generate_django_app)
    print(f"return_code={ret_code}, res={res}")
    if ret_code == 0:
        print('generate app successfully!')
        project_path = os.path.dirname(os.path.dirname(__file__))
        update_app_to_settings(project_path, app_name)
        update_models(project_path, app_name)
        update_base_urls(project_path, app_name)
        return True


def update_app_to_settings(project_path, app_name):
    # project_path = os.path.dirname(os.path.dirname(__file__))
    local_settings_path = os.path.join(project_path, 'backend_django', 'local_settings.py')
    template_base_urls = os.path.join(project_path, "template", "back_end_template", "template_app_settings.html")
    with open(local_settings_path, 'r+') as fw:
        fw_content = fw.read()
        with open(template_base_urls, "r+") as fr:
            fr_content = fr.read().replace("{app}", app_name)
            f_content = fw_content.replace("]", fr_content)
        with open(local_settings_path, "w") as f:
            f.write(f_content)


def generate_vue_page(app_name, table_name):
    project_path = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
    backend_path = os.path.dirname(os.path.dirname(__file__))
    frontend_path = os.path.join(project_path, "frontend_vue3", "src")

    generate_route_file(frontend_path, backend_path, app_name, table_name)
    generate_vue3_page(frontend_path, backend_path, app_name, table_name)


def create_folder_and_file(file_name):
    folder_path, filename = os.path.split(file_name)
    if not os.path.exists(folder_path):
        os.makedirs(folder_path)
    if not os.path.exists(file_name):
        open(file_name, 'w').close()


def generate_route_file(frontend_path, backend_path, app_name, table_name):
    router_file_path = os.path.join(frontend_path, 'router', 'main', app_name, table_name, f'{table_name}.ts')
    template_router = os.path.join(backend_path, "template", "front_end_template", "template_router.html")
    create_folder_and_file(router_file_path)
    with open(router_file_path, "w+") as fw:
        with open(template_router, "r+") as fr:
            fr_content = fr.read().replace("{app_name}", app_name).replace("{table_name}", table_name)
            fw.write(fr_content)


def generate_vue3_page(frontend_path, backend_path, app_name, table_name):
    router_file_path = os.path.join(frontend_path, 'views', 'main', app_name, table_name, f'{table_name}.vue')
    template_vue3 = os.path.join(backend_path, "template", "front_end_template", "template_vue.html")
    with open(router_file_path, "w+") as fw:
        with open(template_vue3, "r+") as fr:
            fr_content = fr.read().replace("{app_name}", app_name).replace("{table_name}", table_name)
            fw.write(fr_content)


def generate_page_content(field_list, frontend_path, backend_path, app_name, table_name):
    # dst_file_path = os.path.join(frontend_path, 'views', 'main', app_name, table_name, 'config', 'content.config.ts')
    dst_file_path = os.path.join(backend_path, "template", "front_end_template", "content.config.ts")
    create_folder_and_file(dst_file_path)
    content = generate_ts_list(field_list, table_name)
    with open(dst_file_path, "w+") as fw:
        fw.write(content)


def generate_ts_list(field_list, table_name):
    temp = {
          'prop': '',
          'label': '',
          'minWidth': '120',
          'sortable': True
        }
    content = {
        'title': f'{table_name} List',
        'showIndexColumn': False,
        'showSelectColumn': False,
        'propList': []
    }
    for i in field_list:
        temp['prop'] = i['field']
        temp['label'] = i['field']
        content['propList'].append(temp)
    typescript_template = """export const contentTableConfig = {0}"""
    json_data = json.dumps(content, indent=2)
    typescript_content = typescript_template.format(json_data)
    return typescript_content


if __name__ == '__main__':
    print("start".center(50, "="))
    # update_app_to_settings('capacity')
    # app_name = "user"
    project_path = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
    print(project_path)
    front_end_path = os.path.join(project_path, "frontend_vue3", "src")
    print(front_end_path)
    # # generate_django_app = f"python manage.py startapp {app_name}"
    # ls = "chdir"
    # ret_code, res = execute_sys_cmd(ls)
    # print(f"return_code={ret_code}, res={res}")
    # create_urls(project_path, app_name)
    # update_base_urls(project_path, 'capacity')
    # update_models(project_path, app_name)
    # generate_views(project_path, app_name)

    field_list = [{'field': 'name'}, {'field': 'user'}]
    backend_path = os.path.dirname(os.path.dirname(__file__))
    frontend_path = os.path.join(project_path, "frontend_vue3", "src")
    app_name = 'capacity'
    table_name = 'capacity'
    generate_page_content(field_list, frontend_path, backend_path, app_name, table_name)
